import React, { Component } from 'react'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { View, Text, Image, ScrollView, Button } from '@tarojs/components'
import { AtTabs, AtTabsPane } from 'taro-ui'
import { Loading, SpNote, SpNavBar, FilterBar } from '@/components'
import api from '@/api'
import { hasNavbar, pickBy } from '@/utils'
import { withPager, withBackToTop } from '@/hocs'
import { AtModal, AtModalHeader, AtModalContent, AtModalAction, AtInput, AtListItem, AtCalendar } from "taro-ui"
import './trade.scss'
import SpPage from '@/components/sp-page'
import ScrollButton from '../../../components/sp-filter-drawer/scroll-button'
import dayjs from 'dayjs'

@withPager
@withBackToTop
export default class DistributionTrade extends Component {
  $instance = getCurrentInstance()
  constructor(props) {
    super(props)

    this.state = {
      ...this.state,
      curTabIdx: 0,
      tabList: [
        { title: '未确认', num: '0' },
        { title: '已确认', num: '0' }
      ],
      filterList: [{ title: '最新', sort: -1 }, { title: '订单金额', sort: -1 }, { title: '佣金', sort: -1 }, { title: '筛选' }],
      list: [],
      query: {},
      shuaixuan: {},
      isOpened: false,
      phone: '',
      start_rebate_point: '',
      end_rebate_point: '',
      time_start_begin: '',
      time_start_end: '',
      showCalendar: false,
      currentDate: {},
      totalOrder: {}
    }
  }

  componentDidMount() {
    this.nextPage()
    // this.setState({
    //   currentDate:{start:dayjs().subtract(6, 'day').format('YYYY-MM-DD'),end:dayjs().format('YYYY-MM-DD'),}
    // })
  }

  async fetch(params) {
    const { curTabIdx, query, phone, start_rebate_point, end_rebate_point, time_start_begin, time_start_end, currentDate } = this.state
    const { type } = this.$instance.router.params
    const { page_no: page, page_size: pageSize } = params
    const query2 = {
      ...query,
      brokerage_source: type,
      page,
      pageSize,
      phone,
      start_rebate_point,
      end_rebate_point,
      time_start_begin: currentDate.start ? dayjs(currentDate.start).unix() : '',
      time_start_end: currentDate.end ? dayjs(currentDate.end).unix() : '',


    }

    const { close, noClose } = await api.distribution.commission(query2)
    const total = curTabIdx == 0 ? noClose.total_count : close.total_count
    const order =  curTabIdx == 0 ? {priceCount: noClose.priceCount,dataCount: noClose.dataCount,rebateCount: noClose.rebateCount}:{priceCount: close.priceCount,dataCount: close.dataCount,rebateCount: close.rebateCount}
    this.setState({
      totalOrder:order
    })
    const nList = pickBy(curTabIdx == 0 ? noClose.list : close.list, {
      order_id: 'order_id',
      rebate: 'rebate',
      created_date: 'created_date',
      headimgurl: 'headimgurl',
      username: 'username',
      mobile: 'mobile',
      commission_type: 'commission_type',
      rebate_point: 'rebate_point',
      item_id: 'item_id',
      item_name: 'item_name',
      item_bn: 'item_bn',
      price: 'price',
      goodsInfo: 'goodsInfo',

    })

    this.setState({
      list: [...this.state.list, ...nList]
    })

    return {
      total
    }
  }
  handleFilterChange = (data) => {
    const { current, sort } = data
    if (current == 3) {
      this.setState({
        isOpened: true
      })
      return
    }
    const query = {
      most_new: current == 0 ? (sort > 0 ? 'ASC' : 'DESC') : '',
      price_sort: current == 1 ? (sort > 0 ? 'ASC' : 'DESC') : '',
      rebate_sort: current == 2 ? (sort > 0 ? 'ASC' : 'DESC') : '',
    }
    this.resetPage()
    this.setState({
      list: []
    })
    this.setState(
      {
        query
      },
      () => {
        this.nextPage()
      }
    )
  }
  handleClickTab = (idx) => {
    if (this.state.page.isLoading) return

    if (idx !== this.state.curTabIdx) {
      this.resetPage()
      this.setState({
        list: []
      })
    }
    this.resetPage()
    this.setState({
      list: []
    })
    this.setState(
      {
        curTabIdx: idx
      },
      () => {
        this.nextPage()
      }
    )
  }

  handleClickConfirm = () => {
    // onConfirm(this.state.query)
    if (parseFloat(this.state.start_rebate_point) > parseFloat(this.state.end_rebate_point)) {
      Taro.showToast({
        title: '佣金数值前者不能大于后者',
        icon: 'none',
        // mask: true
      })
      return
    }
    this.setState({
      isOpened: false,
      showCalendar: false
    })
    this.resetPage()
    this.setState({
      list: []
    }, () => {
      this.nextPage()
    })
  }

  handleConfirm = (isSubmit) => {
    if (isSubmit) {
      if (parseFloat(this.state.start_rebate_point) > parseFloat(this.state.end_rebate_point)) {
        Taro.showToast({
          title: '佣金数值前者不能大于后者',
          icon: 'none',
          // mask: true
        })
        return
      }
      this.setState({
        isOpened: false,
        showCalendar: false
      })
      this.resetPage()
      this.setState({
        list: []
      }, () => {
        this.nextPage()
      })
    } else {
      this.setState({
        phone: '',
        start_rebate_point: '',
        end_rebate_point: '',
        time_start_begin: '',
        time_start_end: '',
        isOpened: false,
        currentDate: {},
        showCalendar: false
      })
      this.resetPage()
      this.setState({
        list: []
      }, () => {
        this.nextPage()
      })
    }
  }
  render() {
    const { list, page, tabList, curFilterIdx, scrollTop, curTabIdx, filterList, isOpened, phone, showCalendar, currentDate, start_rebate_point, end_rebate_point,totalOrder } = this.state
    return (
      <SpPage className='page-distribution-trade'
      >
        <SpNavBar title='订单' leftIconType='chevron-left' />
        <AtTabs
          className={`trade-list__tabs ${hasNavbar && 'trade-list__tabs_web'}`}
          current={curTabIdx}
          tabList={tabList}
          onClick={this.handleClickTab}
        >
          {/* {tabList.map((panes, pIdx) => (
            <AtTabsPane current={curTabIdx} key={pIdx.title} index={pIdx}></AtTabsPane>
          ))} */}
        </AtTabs>
        <FilterBar
          className='trade-list__filtertabs'
          custom
          current={curFilterIdx}
          list={filterList}
          onChange={this.handleFilterChange}
        ></FilterBar>

        <ScrollView
          className={`trade-list__scroll ${hasNavbar && 'trade-list__scroll_web'}`}
          scrollY
          scrollTop={scrollTop}
          onScrollToLower={this.nextPage}
        >
          <View className='trade-list__scroll__section list'>
            {list.map((item) => {
              return (
                <View className='trade-list__scroll__list-item' key={item.order_id} onClick={() => {
                  Taro.navigateTo({ url: `/marketing/pages/distribution/trade-detail?order_id=${item.order_id}` })
                }}>
                  <View className='list-item-header'>
                    <View className='order-no'>
                      <Text className='key'>单号：</Text>
                      {item.order_id}
                    </View>
                    <View className='order-detail'>
                      订单详情
                      <Text className='iconfont icon-arrowRight'></Text>
                    </View>
                  </View>
                  <View className='list-item-detail'>
                    <View className='order-goods'>
                      {item.goodsInfo.map((info,index) =>{
                        if (index <3) {
                          return(
                            <Image
                            className='goods-logo'
                            src={info.pic}
                          />) 
                        } 
                      })}
                    </View>
                    <View className='order-money'>
                      <View className='order-money-one'>
                        <Text className='key'>订单金额：</Text>
                        <Text className='mark'>
                          ¥{item.price / 100}
                        </Text>
                      </View>
                      <View className='order-money-two'>
                        <Text className='key'>本单佣金：</Text>
                        <Text className='mark'>
                          {item.commission_type === 'money' ? (
                            <Text className='cur'>
                              ￥<Text className='commission'>{item.rebate / 100}</Text>
                            </Text>
                          ) : (
                            <Text className='cur'>
                              {' '}
                              <Text className='commission'>{item.rebate_point}积分</Text>
                            </Text>
                          )}
                        </Text>
                      </View>

                    </View>
                  </View>
                  <View className='list-item-detail'>
                    <View className='order-date'>{item.created_date}</View>
                    <View className='member-info'>
                      <Image
                        className='customer-logo'
                        src={item.headimgurl || `${process.env.APP_IMAGE_CDN}/user_icon.png`}
                      />
                      <Text className='customer-phone'>{item.mobile}</Text>
                    </View>
                  </View>

                </View>
              )
            })}
          </View>
          {page.isLoading ? <Loading>正在加载...</Loading> : null}
          {!page.isLoading && !page.hasNext && !list.length && (
            <SpNote img='trades_empty.png'>暂无数据~</SpNote>
          )}
        </ScrollView>
        <View className='page-distribution-trade-footer'>
          <View className='page-distribution-trade-footer-item'>
            <View>统计{currentDate.start ? `(${currentDate.start}至${currentDate.end})` : '(近7日)'}</View>
            <View>订单金额：¥{totalOrder.priceCount}</View>
          </View>

          <View className='page-distribution-trade-footer-item'>

            <View>共{totalOrder.dataCount}单</View>
            <View className='mark'>佣金金额：¥{totalOrder.rebateCount}</View>
          </View>

        </View>
        <AtModal isOpened={isOpened} onClose={() => {
          this.setState({ isOpened: false })
        }}>
          <AtModalHeader>筛选</AtModalHeader>
          <AtModalContent>
            <View>用户账号</View>
          <AtInput
              name='phone'
              type='text'
              placeholder={isOpened ?'请输入用户账号' : ''}
              value={phone}
              onChange={(value) => {
                this.setState({
                  phone: value
                })
              }
              }
            />
            <View>佣金区间(元)</View>
           <View style={{ display: 'flex' }}>
              <AtInput
                name='start_rebate_point'
                type='digit'
                placeholder={isOpened ?'元' : ''}
                adjustPosition
                value={start_rebate_point}
                onChange={(value) => {
                  this.setState({
                    start_rebate_point: value
                  })
                }
                }
              /><View style={{ padding: ' 15px 0', color: '#999' }}>—</View><AtInput
                name='end_rebate_point'
                type='digit'
                placeholder={isOpened ?'元' : ''}
                adjustPosition
                value={end_rebate_point}
                onChange={(value) => {
                  this.setState({
                    end_rebate_point: value
                  })
                }
                }
              />
            </View>

            <AtListItem title='下单日期' hasBorder={false} arrow='right' extraText={currentDate.start ? `${currentDate.start}-${currentDate.end}` : '选择日期'} onClick={() => {
              this.setState({
                showCalendar: true
              })
            }} />
            {showCalendar && <AtCalendar isMultiSelect maxDate={dayjs().format('YYYY-MM-DD')} currentDate={currentDate} onSelectDate={(value) => {
              if (value.value.end) {
                this.setState({
                  showCalendar: false,
                  currentDate: value.value
                })
              }
            }} />}
          </AtModalContent>
          <AtModalAction>  <ScrollButton
            refuseText='重置'
            confirmText='确定并筛选'
            onTransitionEnd={this.handleConfirm}
            onClickConfirm={this.handleClickConfirm}
            isSubmit={() => { }}
          /> </AtModalAction>
        </AtModal>

      </SpPage>
    )
  }
}
